﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';

class NicknameLogic extends GetxController {
  final textController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    // 从参数获取当前昵称
    final currentNickname = Get.arguments as String?;
    if (currentNickname != null) {
      textController.text = currentNickname;
    }
  }

  @override
  void onClose() {
    textController.dispose();
    super.onClose();
  }

  Future<void> save() async {
    if (textController.text.trim().isEmpty) {
      Toast.show( '昵称不能为空');
      return;
    }
    
    try {
      final response = await DefaultApi().editUserPut(
        nickName: textController.text.trim(),
        isShowLoading: true,
      );
      if (response != null && response['code'] == 200) {
        Toast.show( '昵称已更新');
        Get.back(result: textController.text.trim());
      } else {
        Toast.show('更新失败，请重试');
      }
    } catch (e) {
      print('更新昵称失败: $e');
      Toast.show( '更新失败：$e');
    }
  }
}
